<template>
	<view id="bind-id-card-page">
    <!--  绑定银行卡页面  -->
    <BindBankComp
        :btnType="1" :bankInfo="bankInfo"
        v-if="bindBankFlag"
        @finishBankInfo="finishBankInfo"></BindBankComp>
    <!--  身份证操作页面  -->
		<view v-if="!isHand && !bindBankFlag">
			<view class="id-card-box">
				<view class="card">
					<image class="card-img"  @click="selectCardImg('idCardFront')" :src="cardFacadeUrl" mode=""></image>
					<view class="title">上传身份证人像面</view>
				</view>
				<view class="card">
					<image class="card-img" @click="selectCardImg('idCardObverse')" :src="cardBackUrl" mode=""></image>
					<view class="title">上传身份证国徽面</view>
				</view>
			</view>
			<view class="row-list">
				<view class="row-cell">
					<view class="row-cell-title">姓名</view>
<!--					<view class="row-cell-right default-text">-->
<!--						{{cardParam.trueName}}-->
<!--					</view>-->
          <input v-model="cardParam.trueName" class="row-cell-right default-text"/>
				</view>
				<view class="row-cell">
					<view class="row-cell-title">身份证号码</view>
<!--					<view class="row-cell-right default-text">-->
<!--						{{cardParam.idCardNum}}-->
<!--					</view>-->
          <input v-model="cardParam.idCardNum" class="row-cell-right default-text"/>
				</view>
			</view>
			<button class="review-btn" v-if="cardParam.levelType == 2"  @click="changePage(1)">进入身份复核</button>
			<button class="review-btn" v-if="cardParam.levelType == 2"  @click="bindBankFlag = true">进入银行卡绑定</button>
			<view class="description-box">
				<view class="title">绑定身份证说明：</view>
				<view class="content">
					<view>1.请绑定本人身份证，绑定成功后不可修改。</view>
					<view>2.请确认你本人的身份证真实有效，上传虚假身份证将对你的账号进行封号处理。</view>
					<view>3.平台对身份证图片加有水印，信息安全保护中身份证只有用于平台验证，无法二次使用。</view>
				</view>
			</view>
			<button class="sumbit-btn" :loading="loading" :disabled="loading" @click="banding()">提交</button>
		</view>
    <!--  身份证操作页面  -->
		<view v-if="isHand">
			<view id="idCard-hand-page">
				<view class="title">系统随机生成指定手势数字</view>
				<view class="random-number themeColor">{{cardParam.randNum}}</view>
				<view class="tips">右手持身份证放置于胸前，左手做出指定手势数字</view>
				<view class="tips">点击下面的图片，进行上传。</view>
				<view class="handheld-card-box" @click="selectCardImg('idCardHand')">
					<image class="handheld-card-img" :src="cardHandUrl"></image>

				</view>
				<button class="sumbit-btn"  @click="changePage(2)">完成</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		apiBindPushUserInfo,
		apiBankIdCardBind,
		apiUploadToken
	} from '../../../http/apis.js'
	import {
		mapState
	} from 'vuex'
	import qiniuUploader from '../../components/qiniu/qiniuUploader.js';
	import BindBankComp from "./BindBankComp";

	export default {
	  components: {
      BindBankComp
    },
		computed: {
			...mapState(['token'])
		},
		data(){
			return{
        bindBankFlag: false,
        bankInfo: {},// 回传给银行卡页面
				cardFacadeUrl: '../../static/img/card_face.png',
				cardBackUrl: '../../static/img/card_back.png',
				cardHandUrl: '../../static/img/handheld_card.png',
				cardParam:{
					token: '',
					idCardFront: '',
					idCardObverse: '',
					idCardHand: '',
					trueName: '',
					address: '',
					sex: '',
					idCardNum: '',
					birthday:'',
					submitType: 1,
					system: '',
					levelType: '',
					randNum: ''
				},
				loading: false,
				uploadToken: '',
				successFlag: false,
				isHand: false,
				isUploadSuccess: false
			}
		},
		onShow() {
			apiUploadToken({}).then(res =>{
			    if(res.data.code == 1)  {
					this.uploadToken = res.data.msg
				}
			}).catch(res => {
				this.$msg.showToast(res.data.msg)
			})

			// this.getInitData()
		},
		onLoad(options) {
			this.cardParam.levelType = options.levelType
			this.cardParam.token = this.token
			uni.getSystemInfo({
			    success: (res)=> {
			       this.cardParam.system = res.platform == 'ios' ? 12 :11
			    }
			})
		},
		methods:{
      finishBankInfo(bankInfo) {
        this.bindBankFlag = false
        this.bankInfo = bankInfo
        Object.assign(this.cardParam, bankInfo)
        this.cardParam.token = this.token
        // console.log("银行卡信息填写完成:", bankInfo, this.cardParam)
      },
			getInitData(){
				apiBindPushUserInfo({
					token: this.token
				}).then(res =>{
				    if(res.data.code == 1)  {
						var result = res.data.msg
						this.cardParam = {
							token: this.token,
							idCardFront: result.id_card_front,
							idCardObverse: result.id_card_obverse,
							idCardHand: result.id_card_hand,
							randNum: result.randNum,
							trueName: result.true_name,
							address: result.address ? result.address : '',
							sex: result.sex == 99 ? '' : result.sex,
							idCardNum: result.id_card_num,
							birthday: result.age == 99 ? '' : result.age,
							submitType: 1,
							system: this.cardParam.system,
							levelType: result.level_type
						}
					}
				}).catch(res => {
					this.$msg.showToast(res.data.msg)
				})
			},
			changePage(type){
				if(type == 2){
					if(!this.cardParam.idCardHand){
						this.$msg.showToast('请先上传手持身份证')
						return
					}
				} else {
				   this.cardParam.randNum = parseInt(Math.random() * 5) + 1
				}
				this.isHand = type == 1 ? true : false

			},
			uploadImg(typeimg,typezfm,fileSize){
				uni.showLoading({
					title: '上传中',
					mask: true
				})
				var that = this;
				uni.getImageInfo({
					src:typeimg.tempFilePaths[0],
					success(res) {
						let canvasWidth = res.width //图片原始长宽
						let canvasHeight = res.height
						let img = new Image()
						img.src = res.path
						let canvas = document.createElement('canvas');
						let ctx = canvas.getContext('2d')
						let scale = res.height/res.width
						canvas.width = fileSize == true ? 500 : canvasWidth
						canvas.height = fileSize == true ? 500*scale : canvasHeight
						ctx.drawImage(img, 0, 0, fileSize == true ? 500 : canvasWidth , fileSize == true ? 500*scale : canvasHeight )//fileSize == true ? 300 : canvasHeight / 2

						canvas.toBlob(function(fileSrc) {
							let imgSrc = window.URL.createObjectURL(fileSrc)
							var random = Math.floor(Math.random() * (1000 - 1)) + 1
							var timestamp=new Date().getTime();
							var name=imgSrc.substring(imgSrc.lastIndexOf("-")+1);
							var key = name + random.toString() + timestamp.toString() + '.png'
							 qiniuUploader.upload(
							    imgSrc,
                  res => {
							      //图片上传完成后返回值
                    uni.hideLoading()
                    that.$msg.showToast('上传成功')
                    if(typezfm == 'idCardFront'){
                      that.cardParam.idCardFront = res.imageURL;
                      that.identifyIdCard(that.cardParam.idCardFront,'face')
                    }else if(typezfm == 'idCardObverse'){
                      that.cardParam.idCardObverse = res.imageURL;
                      that.identifyIdCard(that.cardParam.idCardObverse,'back')
                    } else {
                      that.cardParam.idCardHand = res.imageURL;
                    }
							    },
							    error => {
							      console.log(error)
                    uni.hideLoading()
                    that.$msg.showToast('上传失败')
							    },
							    {
							        region: that.GLOBAL.REGION_VALUE, // （必须填写正确）ECN, SCN, NCN, NA, ASG，分别对应七牛的：华东，华南，华北，北美，新加坡 5 个区域
							        domain: that.GLOBAL.QINIU_URL, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL                                         字  段。否则需要自己拼接
							        key: 'idCard/' + key, // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
							        // 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
							        uptoken: that.uploadToken // 由其他程序生成七牛 uptoken
							    },
							    res => {
							      //上传进度
                    if(res.progress === 100){
                      uni.hideLoading()
                    }
							    }
							);
						})
					}
				})

			},
			identifyIdCard (img,type){
				if(img.indexOf('idCard') < 0){
					this.$msg.showToast('图片上传失败，请重新上传')
					return
				}
				uni.showLoading({
					title: '识别中',
					mask: true
				})
				uni.request({
					url:this.GLOBAL.BASE_URL+'baseapi/push/idCardOrc',
					method:'POST',
				    data:{
					    token: this.token,
						imageUrl: img,
						side: type //face正面 back反面
				    },success:res=>{
						uni.hideLoading()
						if (res.data.code == 1) {
							if(res.data.msg.indexOf('Invalid')>= 0){
								this.$msg.showToast('识别失败，请重新上传正确的身份证照片')
								return
							}
							if(type == 'face'){
								var data = JSON.parse(res.data.msg)
								this.cardParam.birthday = data.birth
								this.cardParam.trueName = data.name
								this.cardParam.sex = data.sex
								this.cardParam.idCardNum = data.num
								this.cardParam.bankUserName = data.name
								this.cardParam.address = data.address
								this.successFlag = true
							} else {
								this.isUploadSuccess = true
							}
							this.$msg.showToast('识别成功')
						} else {
							if(type == 'back'){
								this.isUploadSuccess = false
							}
							this.$msg.showToast(res.data.msg)
						}

				    }
				})
			},
			selectCardImg(type){
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original','compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: (res)=> {
						if(type == 'idCardFront'){
							this.cardFacadeUrl = res.tempFilePaths[0]
						} else if(type == 'idCardObverse'){
							this.cardBackUrl = res.tempFilePaths[0]
						} else {
							this.cardHandUrl = res.tempFilePaths[0]
						}
						this.uploadImg(res,type, res.tempFiles[0].size > 1570000);
					}
				});
			},
			banding(){
				if(!this.cardParam.idCardFront){
					this.$msg.showToast('请上传身份证正面照片')
					return
				}
				if(this.cardParam.idCardFront.indexOf('idCard') < 0){
					this.$msg.showToast('未获取到身份证正面照片，请重新上传')
					return
				}
				if(!this.successFlag){
					this.$msg.showToast('请上传正确的身份证正面照片')
					return
				}
				if(!this.isUploadSuccess){
					this.$msg.showToast('请上传正确的身份证反面照片')
					return
				}
				if(!this.cardParam.idCardObverse){
					this.$msg.showToast('请上传身份证反面照片')
					return
				}
				if(this.cardParam.idCardObverse.indexOf('idCard') < 0){
					this.$msg.showToast('未获取到身份证反面照片，请重新上传')
					return
				}
				if(this.cardParam.levelType == 2){
					if(!this.cardParam.idCardHand){
						this.$msg.showToast('请先进行身份复核')
						return
					}
					if(this.cardParam.idCardHand.indexOf('idCard') < 0){
						this.$msg.showToast('未获取到手持身份证照片，请重新上传')
						return
					}
				}

				uni.showLoading({
					title: '提交中',
					mask: true
				})
				this.loading = true
				apiBankIdCardBind(this.cardParam).then(res =>{
					uni.hideLoading()
          this.loading = false
          if(res.data.code == 1)  {
            // 移除非必要参数
            delete this.bankInfo.region
						this.$msg.showToast('绑定成功')
						setTimeout(()=>{
							uni.switchTab({
								url:'../profile/a'
							})
						},500)
					} else {
						this.$msg.showToast(res.data.msg)
					}
				}).catch(res => {
					uni.hideLoading()
					this.loading = false
					this.$msg.showToast(res.data.msg)
				})
			}

		}
	}
</script>

<style lang="scss">
	page{
		background: #F5F5F5;
	}
	#bind-id-card-page{
		.id-card-box {
			display: flex;
			justify-content: center;
			// background: #FFFFFF;
			// margin-bottom: 32upx;
			.card {
				text-align: center;
				margin: 32upx 0;

				.card-img {
					width: 340upx;
					height: 200upx;
					margin: 0 12upx;
					border: 1px solid rgb(23,193,190);
				}
				.title {
					font-size: 28upx;
					font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #888888;
					line-height: 48upx;
				}
			}
		}
		.row-list {
			background: #FFFFFF;
			margin-bottom: 32upx;
			.row-cell {
				position: relative;
				border-bottom: 1px solid #E8E8E8;
				padding: 0 24upx 0 38upx;
				height: 106upx;
				line-height: 106upx;

				.row-cell-title {
					display: inline-block;
					font-size: $font-base;
					color: #333333;
					font-size: 30upx;
					width: 180upx;
				}
				.row-cell-right {
					display: inline-block;
					font-size: 30upx;
					width: 72%;
					vertical-align: middle;
					&.default-text {
						color: #999999;
					}
					.input {
						padding: 10upx 0;
						color: #333333;
						font-size: 30upx;
						.uni-input-placeholder {
							color: #999999;
						}
					}
				}
			}
		}
		.review-btn {
			margin: 32upx 140upx;
			height: 80upx;
			background: #FF8C00;
			border-radius: 10upx;
			font-size: 32upx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
			line-height: 80upx;
		}
		.description-box {
			background: #FFFFFF;
			padding: 32upx;
			.title{
				font-size: 28upx;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #333333;
				line-height: 30upx;
				margin-bottom: 32upx;
			}
			.content {
				font-size: 28upx;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #999999;
				line-height:44upx;
			}
		}
		.sumbit-btn {
			margin: 32upx;
			height: 96upx;
			background: $theme-color;
			border-radius: 10upx;
			font-size: 32upx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
			line-height: 96upx;
		}
	}
	#idCard-hand-page {
		text-align: center;
		padding: 20upx;
		background: #FFFFFF;
		.title {
			font-size: 30upx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 48upx;
		}
		.random-number {
			border: 1px dashed #E0E0E0;
			font-size: 80upx;
			display: inline-block;
			padding: 88upx 120upx;
			border-radius: 100%;
			margin: 20upx 0;
			color: $theme-color;
		}
		.tips {
			font-size: 30upx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: $theme-color;
			line-height: 48upx;
		}
		.handheld-card-box {
			width: 100%;
			height: 380upx;
			border: 1px dashed #E0E0E0;
			border-radius: 10upx;
			margin: 40upx 0;
			.handheld-card-img {
				width: 100%;
				height: 100%;
				border-radius: 10upx;
			}
		}
		.sumbit-btn {
			margin: 32upx;
			height: 96upx;
			background: $theme-background-color;
			border-radius: 10upx;
			font-size: 32upx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: rgba(255, 255, 255, 1);
			line-height: 96upx;
		}
	}
</style>
